package com.shenjinzheng.dk.sso.service.impl.auth;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shenjinzheng.dk.sso.config.WeChatConfig;
import com.shenjinzheng.dk.sso.service.UserAuthService;
import com.shenjinzheng.dk.sso.service.UserService;
import com.shenjinzheng.dk.sso.utils.utils.JwtUtil;
import com.shenjinzheng.dk.sso.wechat.WeChatAPI;
import com.shenjinzheng.sso.bo.OpenIdBO;
import com.shenjinzheng.sso.dto.LoginDTO;
import com.shenjinzheng.sso.entity.User;
import com.shenjinzheng.sso.vo.UserLoginVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @author shenjinzheng
 */
@Slf4j
@Service("weChatAuthService")
public class WeChatAuthServiceImpl implements UserAuthService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private WeChatConfig weChatConfig;

    @Resource
    private UserService userService;

    @Override
    public void sendCode(String phone) {
        throw new RuntimeException("微信登录不需要发送验证码");
    }

    @Override
    public UserLoginVO login(LoginDTO loginDTO) {
        String url = WeChatAPI.jscode2session;
        url = url.replace("{APPID}", weChatConfig.getAppid());
        url = url.replace("{SECRET}", weChatConfig.getSecret());
        url = url.replace("{CODE}", loginDTO.getCode());

        String str = restTemplate.getForObject(url, String.class);
        OpenIdBO bo = JSON.parseObject(str, OpenIdBO.class);
        log.info("{}", bo);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenId, bo.getOpenid());
        User user = userService.getOne(wrapper);
        UserLoginVO userLoginVO = new UserLoginVO();
        if (user == null) {
            //说明该用户微信未绑定手机号(将openid返回给前端,与手机号绑定)
            userLoginVO.setOpenId(bo.getOpenid());
            return userLoginVO;
        }
        //如果不为空,该用户已经绑定手机号,直接返回token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("role", "user");
        String token = jwtUtil.createToken(map);

        userLoginVO.setId(user.getId());
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
